#include "TokenBoolExp.h"
#include "TokenIntExp.h"
#include "Value.h"
#include "Error.h"
#include <string>
#include <sstream>
#include <cassert>
using namespace std;
void TokenBool::run(bool enabled /*= true*/)
{
	if (toParse == "")
		throw Error("Bool token expected but not found.");
	string boolWord, word;
	istringstream sin(toParse);
	sin >> boolWord;
	if (boolWord == "True")
	{
		result = new bool(true);
		sin >> word;
		if (word != "")
			throw Error("Unexpected \"" + word + "\" after bool token.");
	}
	else if (boolWord == "False")
	{
		result = new bool(false);
		sin >> word;
		if (word != "")
			throw Error("Unexpected \"" + word + "\" after bool token.");
	}
	else
	{
		TokenIntExp tie(toParse);
		ValueInt vi = tie.getResult();
		result = new bool(vi.cmp(0) != 0);
	}
}
void TokenBoolCmp::run(bool enabled /*= true*/)
{
	if (toParse == "")
		throw Error("Bool expression in comparison form expected but not found.");
	int opp; // operator position
	int opc; // operator charater
	const int CmpSymNum = 7;
	string CmpSymbol[CmpSymNum] = {"==", "!=", "<>", "<=", "<", ">=", ">"}; // < is substring of <=, so <= must come first!
	for (opc = 0; opc < CmpSymNum; opc++)
	{
		opp = toParse.find(CmpSymbol[opc]);
		if (opp != string::npos)
			break;
	}
	if (opc == CmpSymNum) // or >= ?
	{
		TokenBool tb(toParse);
		result = new bool(tb.getResult());
		return;
	}
	TokenIntExp* rhs = new TokenIntExp(toParse.substr(opp+CmpSymbol[opc].size(), toParse.size()-CmpSymbol[opc].size()-opp));
	ValueInt rhsr = rhs -> getResult();
	TokenIntExp* lhs = new TokenIntExp(toParse.substr(0, opp));
	ValueInt lhsr = lhs -> getResult();
	switch (opc)
	{
	case 0:
		result = new bool(lhsr.cmp(rhsr) == 0);
		break;
	case 1:
	case 2:
		result = new bool(lhsr.cmp(rhsr) != 0);
		break;
	case 3:
		result = new bool(lhsr.cmp(rhsr) <= 0);
		break;
	case 4:
		result = new bool(lhsr.cmp(rhsr) < 0);
		break;
	case 5:
		result = new bool(lhsr.cmp(rhsr) >= 0);
		break;
	case 6:
		result = new bool(lhsr.cmp(rhsr) > 0);
		break;
	}
}
void TokenBoolExp::run(bool enabled /*= true*/) // to later support and or not
{
	if (toParse == "")
		throw Error("Bool expression expected but not found.");
	TokenBoolCmp tbc(toParse);
	if (result != NULL)
		delete result;
	result = new bool(tbc.getResult());
}

